package org.donald.strategy;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class CustomTablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
    /**
     *
     * @param dataSourceNames 数据源集合
     * 在分库时值为所有分⽚库的集合databaseNames
     * 分表时为对应分⽚库中所有分⽚表的集合 tablesNames
     *
     * @param shardingValue 分⽚属性，包括 logicTableName 为逻辑表，
     * columnName 分⽚健（字段），
     * value 为从SQL 中解析出的分⽚健的值
     */
    @Override
    public String doSharding(Collection<String> dataSourceNames,
                             PreciseShardingValue<Long> shardingValue) {
        for (String databaseName : dataSourceNames) {
            String value = shardingValue.getValue() % dataSourceNames.size() + "";
            //value是0，则进⼊0库表，1则进⼊1库表
            if (databaseName.endsWith(value)) {
                return databaseName;
            }
        }
        throw new IllegalArgumentException();
    }
}
